const saveOptions = (options) => {
  chrome.storage.local
    .set({
      rulesets: options,
    })
    .catch(console.error);
};

const setupOptions = (rulesets) => {
  const fragment = document.createDocumentFragment();
  for (const ruleset of rulesets) {
    const div = document.createElement("div");
    div.insertAdjacentHTML(
      "beforeend",
      `<input id="${ruleset.id}" name="${ruleset.id}" type="checkbox" ${ruleset.enabled ? 'checked' : ''}/>`
    );
    div.insertAdjacentHTML(
      "beforeend",
      `<label for=${ruleset.id}>${chrome.i18n.getMessage(ruleset.id) ?? ruleset.id}</label>`
    );
    fragment.append(div);
  }
  const optionsContainer = document.getElementById("options");
  optionsContainer.appendChild(fragment);
};

document.addEventListener("DOMContentLoaded", () => {
  chrome.storage.local
    .get({ rulesets: [] })
    .then(({ rulesets }) => setupOptions(rulesets))
    .catch(console.error);
  document.getElementById("save").addEventListener("click", (event) => {
    event.preventDefault();
    const checkboxs = document.querySelectorAll("#options input[type=checkbox]");
    const options = Array.from(checkboxs).map((radio) => {
      return {
        id: radio.getAttribute("name"),
        enabled: radio.checked,
      };
    });
    saveOptions(options);
    window.close();
  });
});
